/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.bean.chart;

import com.bean.chart.iterfaces.AbstractChartUnit;
import java.awt.*;
import java.beans.PropertyChangeSupport;
import java.io.Serializable;
import javax.swing.JComponent;

/**
 *
 * @author Lukasz
 */
public class ChartUnit extends JComponent implements AbstractChartUnit, Serializable{

    public static final String PARAM_NAME_UNIT = "unit_property";
    public static final String PARAM_NAME_UNITBCKGCOLOR = "unit_bckgcolor_property";
    public static final String PARAM_NAME_UNITCOLOR = "unit_color_property";
    private PropertyChangeSupport propertySupport;
    private String unit = "Unit";
    private int size;
    private Color unitColor = Color.BLACK;
    private Color unitBckgColor = Color.WHITE;
    public ChartUnit(){
        propertySupport = new PropertyChangeSupport(this);

    }
    @Override
    public void setUnit(String unit) {
        String oldUnit = this.unit;
        this.unit = unit;
        validate();
        repaint();
        propertySupport.firePropertyChange(PARAM_NAME_UNIT, oldUnit, unit);
    }

    @Override
    public String getUnit() {
        return unit;
    }
    
     @Override
    public void setUnitColor(Color color) {
        Color oldColor = this.unitColor;
        this.unitColor = color;
        propertySupport.firePropertyChange(PARAM_NAME_UNITCOLOR, oldColor, oldColor);
    }

    @Override
    public Color getUnitColor() {
        return unitColor;
    }
    
    @Override
    public void setUnitBackground(Color color) {
        Color oldColor = this.unitBckgColor;
        this.unitBckgColor = color;
        propertySupport.firePropertyChange(PARAM_NAME_UNITBCKGCOLOR, oldColor, oldColor);
    }

    @Override
    public Color getUnitBackground() {
        return unitBckgColor;
    }
    @Override
    public void paintComponent(Graphics g){
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D)g;
        g2.setColor(unitBckgColor);
        g2.fillRect(0, 0, getSize().width, getSize().height);
        g2.setColor(unitColor);
        drawCenteredString(unit, getSize().width, getSize().height, g2);
       
     
    }
    
    private void drawCenteredString(String s, int w, int h, Graphics2D g2) {
    FontMetrics fm = g2.getFontMetrics();
    size = fm.stringWidth(unit);
    size = size + 20;
    this.setPreferredSize(new Dimension(size ,getSize().height));
    int x = (w - fm.stringWidth(s)) / 2;
    int y = (fm.getAscent() + (h - (fm.getAscent() + fm.getDescent())) / 2);
    g2.drawString(s, x, y);
  }
}
